package com.fly.feishu.domain.service.impl;

import com.fly.feishu.api.dto.DeptCondition;
import com.fly.feishu.api.dto.DeptSyncDto;
import com.fly.feishu.api.dto.EmployeeSyncDto;
import com.fly.feishu.api.service.FeishuContractService;
import com.fly.feishu.domain.enums.DataSyncType;
import com.fly.feishu.domain.service.DeptSyncService;
import com.fly.feishu.domain.service.EmpSyncService;
import com.fly.feishu.infrastructure.persistent.mapper.EmpDeptMapper;
import com.fly.feishu.infrastructure.persistent.mapper.EmployeeMapper;
import com.fly.feishu.infrastructure.persistent.po.Employee;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
@Slf4j
public class EmpSyncServiceImpl implements EmpSyncService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private EmpDeptMapper empDeptMapper;
    @Autowired
    private DeptSyncService deptSyncService;
    @Autowired
    private FeishuContractService feishuContractService;

    @Override
    public void sync(Long id, DataSyncType type) {
        Example example = new Example(Employee.class);
        example.createCriteria().andEqualTo("id", id);
        Employee employee = employeeMapper.selectOneByExample(example);
        if (employee == null) {
            log.warn("员工数据同步，未查询到本地数据，ID = {}", id);
            return;
        }

        // 员工离职
        if ("I".equals(employee.getStatus())) {
            type = DataSyncType.DELETE;
        }
        switch (type) {
            case POST:
                post(employee);
                break;
            case PUT:
                put(employee);
                break;
            case DELETE:
                delete(id);
                break;
            default:
                log.warn("员工数据同步，不支持的操作类型：type = {}, ID = {}", type.name(), id);
        }
    }

    private void post(Employee employee) {
        feishuContractService.createEmployee(convertEntity2Dto(employee, true));
    }

    private void put(Employee employee) {
        feishuContractService.updateEmployee(convertEntity2Dto(employee, true));
    }

    private void delete(Long id) {
        feishuContractService.employeeLeave(id.toString());
    }

    private EmployeeSyncDto convertEntity2Dto(Employee employee, boolean isUpdateDept) {
        EmployeeSyncDto employeeSyncDto = new EmployeeSyncDto();
        employeeSyncDto.setUserId(employee.getId().toString());
        employeeSyncDto.setName(employee.getName());
        employeeSyncDto.setCity(employee.getCity());
        employeeSyncDto.setCountry(employee.getCountry());
        employeeSyncDto.setEmail(employee.getEmail());
        employeeSyncDto.setEmployeeType(employee.getEmployeeType());
        employeeSyncDto.setEmployeeNo(employee.getEmployeeNo());
        employeeSyncDto.setGender(employee.getGender());
        employeeSyncDto.setJoinTime(employee.getJoinTime().getTime() / 1000);
        employeeSyncDto.setWorkStation(employee.getWorkStation());
        employeeSyncDto.setMobile(employee.getMobile());
        if (isUpdateDept) {
            List<String> deptIds = empDeptMapper.getDeptIdByEmpId(employee.getId());
            Set<String> deptIdSet = Sets.newHashSet();
            if (!CollectionUtils.isEmpty(deptIds)) {
                deptIds.stream().forEach(deptId -> {
                    DeptCondition deptCondition = new DeptCondition();
                    deptCondition.setDepartmentId(deptId);
                    DeptSyncDto dept = feishuContractService.getDept(deptCondition);
                    if (dept == null) {
                        try {
                            deptSyncService.sync(Long.parseLong(deptId), DataSyncType.POST);
                        } catch (Exception e) {
                            log.error("员工数据同步，部门数据同步失败，originDeptId = {}", deptId, e);
                            return;
                        }
                    }
                    deptIdSet.add(deptId);
                });
                employeeSyncDto.setDepartmentIds(new ArrayList<>(deptIdSet));
            }
        }
        return employeeSyncDto;
    }
}
